const db = require("../db/index");
const bcrypt = require("bcryptjs");
const { generateToken } = require("../util/token");

exports.regUser = (req, res) => {
  const userinfo = req.body;
  const sql = "select * from users where username=?";
  db.query(sql, [userinfo.username], (err, results) => {
    if (err) return res.cc(err);
    if (results.length > 0) {
      return res.cc("用户名被占用，请更换其他用户名！");
    }
    userinfo.password = bcrypt.hashSync(userinfo.password, 10);
    const sql = "insert into users set ?";
    const user = {
      username: userinfo.username,
      password: userinfo.password,
      nickname: userinfo.nickname,
      email: userinfo.email,
      avatar: userinfo.avatar,
      role: userinfo.role,
      created_at: new Date(),
      last_login: new Date(),
      website: userinfo.website,
      bio: userinfo.bio,
      phone: userinfo.phone,
    };
    db.query(sql, user, (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) {
        return res.cc("注册用户失败，请稍后再试！");
      }
      res.cc("注册成功！", 0);
    });
  });
};

exports.login = (req, res) => {
  const userinfo = req.body;
  const sql = "select * from users where username=?";
  db.query(sql, userinfo.username, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("登录失败！请检查用户名是否正确");
    const compareResult = bcrypt.compareSync(
      userinfo.password,
      results[0].password
    );
    if (!compareResult) return res.cc("登录失败！密码错误!");
    const sql = "update users set last_login=? where id=?";
    db.query(sql, [new Date(), results[0].id], (err, results) => {
      if (err) return res.cc(err);
      if (results.affectedRows !== 1) {
        return res.cc("登录失败！");
      }
    });
    const user = { ...results[0], password: "" };
    const tokenStr = generateToken(user);
    res.send({
      status: 0,
      message: "登录成功！",
      token: "Bearer " + tokenStr,
      user: user,
    });
  });
};

// 获取用户信息接口
exports.getUserInfo = (req, res) => {
  const userId = req.params.id;
  const sql = "select * from users where id=?";
  db.query(sql, userId, (err, results) => {
    if (err) return res.cc(err);
    if (results.length !== 1) return res.cc("获取用户信息失败！");
    const user = { ...results[0], password: "" };
    res.send({
      status: 0,
      message: "获取用户信息成功！",
      user: user,
    });
  });
};

exports.getUserArticles = (req, res) => {
  const userId = req.params.id;
  console.log(userId);

  const sql = "select * from article where user_id=?";
  db.query(sql, userId, (err, results) => {
    if (err) return res.cc(err);
    if (results.length === 0) {
      return res.send({
        status: 0,
        message: "该用户没有文章！",
        articles: [],
      });
    }
    res.send({
      status: 0,
      message: "获取用户文章成功！",
      articles: results,
    });
  });
};
